<?php
/**
 * Created by PhpStorm.
 * User: ycp
 * Date: 2019/5/23
 * Time: 22:23
 */

namespace app\api\controller;




use app\common\facade\Func;
use think\Db;

class Activity extends ApiCommon
{
    protected $service;
    protected $table = 'lite_activity';
    protected $groupTable = 'lite_activity_group';
    protected $packageTable = 'lite_activity_package';
    protected $goodsTable = 'lite_activity_product';
    protected $cateTable = 'lite_activity_cate';
    protected $memberTable = 'store_member';

    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
       $where = ['is_deleted' => 0, 'is_show_index' => 1, 'status' => [0, 1]];
       //总数量
       $totalSize = db($this->table)->where($where)->count();
       //当前页码
       $current_page = $this->request->param('pageNum', 1);
       //分页大小
       $size = $this->request->param('size', 3);

       $list = db($this->table)->where($where)->limit(($current_page - 1) * $size, $size)->order('sort', 'desc')->order('id', 'desc')->select();
//        $activityIds = array_column($list, 'id');
        //获取最低价格
//        $groupMinPrice = db($this->groupTable)->where(['activity_id' => $activityIds])->group('activity_id')->column('activity_id,min(price)');
//        $packageMinPrice = db($this->packageTable)->where(['activity_id' => $activityIds])->group('activity_id')->column('activity_id,min(price)');

       foreach ($list as $key => $val){
           $applyEndTime = strtotime($list[$key]['apply_end_time']);
//           if($applyEndTime > time()){
//               $dateFormat = $this->getDateFormat($applyEndTime);
//               $list[$key]['day'] = $dateFormat['day'];
//               $list[$key]['hour'] = $dateFormat['hour'];
//               $list[$key]['minute'] = $dateFormat['minute'];
//           }else{
//               $this->setActivityStatus($val['id'], $applyEndTime);
//               unset($list[$key]);
//               continue;
//           }

//           $list[$key]['activityId'] = $val['id'];

           $dateFormat = $this->getDateFormat($applyEndTime);
           $list[$key]['day'] = $dateFormat['day'];
           $list[$key]['hour'] = $dateFormat['hour'];
           $list[$key]['minute'] = $dateFormat['minute'];

           $list[$key]['start_time'] = substr($list[$key]['start_time'], 0, 10);
//           $list[$key]['minPrice'] = min([isset($groupMinPrice[$val['id']]) ? $groupMinPrice[$val['id']]: 0, isset($packageMinPrice[$val['id']]) ? $packageMinPrice[$val['id']]: 0]);
//           if(isset($packageMinPrice[$val['id']]) && isset($groupMinPrice[$val['id']])){
//               $list[$key]['minPrice'] = min([$groupMinPrice[$val['id']], $packageMinPrice[$val['id']] ]);
//           }else{
//               $list[$key]['minPrice'] = isset($groupMinPrice[$val['id']]) ? $groupMinPrice[$val['id']]:0;
//           }
           $list[$key]['minPrice'] = $list[$key]['show_price'];
           $list[$key]['minPrice'] = round($list[$key]['minPrice'], 1);
           $list[$key]['pic'] = $this->getImageDir($list[$key]['pic']);
           //城市
           if($val['country'] == '中国'){
               $city = [$val['province'], $val['city']];
               $list[$key]['city'] = implode('-', array_filter($city));
           }else{
               $city = [$val['country'], $val['province'], $val['city']];
               $list[$key]['city'] = implode('-', array_filter($city));
           }
       }

       $res = [];
       $res['list'] = $list;
       $res['current_page'] = $current_page;
       $res['totalSize'] = $totalSize;
       $res['pageSize'] = ceil($totalSize / $size);

       $this->success('', $res);
    }

    public function getDateFormat($date){
        $time = $date - time();
        $res['day'] = floor($time / (24*3600));
        $res['hour'] = floor(($time - $res['day']*24*3600 ) / 3600);
        $res['minute'] = floor(($time - $res['day']*24*3600 - $res['hour'] * 3600) / 60);
        return $res;
    }

    private function setActivityStatus($id, $applyEndTime)
    {
        return db($this->table)->where(['id' => $id])->update(['status' => 2]);
    }

    //获取活动详情
    public function detail()
    {
        $id = $this->request->param('id');
        if($id){
            $data = $this->__detail($id);
            $this->success('', $data);
        }
    }

    public function __detail($id, $detail = false){
        $typeData = config('data.activity_type');
        $data = db($this->table)->where(['id' => $id])->find();
        //类别
        $data['cate'] = db($this->cateTable)->where(['activity_id' => $id])->column('id, cate_id', 'id');
        if(in_array('8',$data['cate']) || $data['type'] == 8){
            $data['isCate'] = true;
        }
        $data['pic'] = $this->getImageDir($data['pic']);
        $data['type'] = $typeData[$data['type']]['name'];
        $data['start_time'] = substr($data['start_time'], 0 ,10);
//            $data['apply_end_time'] = substr($data['apply_end_time'], 5,2);
        $limit = $this->getYearMonthDay($data['apply_end_time']);
        $data['apply_end_time_day'] = $this->getDateFormat(strtotime($data['apply_end_time']))['day'] . '天(报名即止)';
        $data['apply_end_time'] = $limit['month'] . $limit['day'];
        if(!empty($data['image'])){
            $data['image'] = explode('|', $data['image']);
            foreach ($data['image'] as $imageKey => $image){
                $data['image'][$imageKey] = [];
                $data['image'][$imageKey]['pic'] = $this->getImageDir($image);
                $data['image'][$imageKey]['type'] = 'image';
            }
        }
//            $data['longitude'] = Func::coordinateTranslate('GCJ-02', 'BD-09', [$data['longitude'], $data['latitude']])[0];
//            $data['latitude'] = Func::coordinateTranslate('GCJ-02', 'BD-09', [$data['longitude'], $data['latitude']])[1];
        //获取活动关联信息
        //组别
        $data['group'] = $this->getRelationGroupData($data['id']);
        //套餐
        $data['package'] = $this->getRelationPackageData($data['id']);
        //服务
        $data['goods'] = $this->getRelationGoodsData($data['id'], $detail);
        //地址
        $data['addressData'] = db('StoreMemberAddress')
            ->where(['mid' => $this->openid])
            ->order('is_default desc,id desc')
            ->find();



        return $data;
    }

    protected function getRelationGroupData($id){
        return db($this->groupTable)->field('id,activity_id,name,price,status')->where(['is_deleted' => 0, 'activity_id' => $id])->select();
    }
    protected function getRelationPackageData($id){
        $data = db($this->packageTable)->where(['is_deleted' => 0, 'activity_id' => $id])->select();
        foreach ($data as $key => $package){
            $data[$key]['room_type'] = config('data.room_type')[$package['room_type']];
            $data[$key]['price'] = round($data[$key]['price'], 0);
            $data[$key]['list_price'] = round($data[$key]['list_price'], 0);
        }
        return $data;
    }

    protected function getYearMonthDay($date){
        $time = strtotime($date);
        $res['year'] = date('Y', $time);
//        $res['month'] = strpos(substr($date, 5,2), 0) ? substr($date, 6,1) . '月': substr($date, 5,2) . '月';
        $res['month'] = date('n月', $time);
        $res['day'] = date('j日', $time);
        return $res;
    }

    public function search()
    {
        $data = $this->request->param('option');

        $where = [
            ['is_deleted', '=', 0]
        ];

        //搜索
        if(!empty($data['search'])){
            if(isset($data['search']['type']) && $data['search']['type'] != -1){
                $cate = config('data.activity_type');
//            $where[] = ['type', 'in', $data['cateId']];
                $activityIds = db('lite_activity_cate')->where('cate_id', '=', $data['search']['type'])->column('id, activity_id', 'id');
                $where[] = ['id', 'in', array_unique($activityIds)];
                $optionRes['cate']['title'] = $cate[$data['search']['type']]['name'];
                $optionRes['cate']['value'] = $data['search']['type'];
            }else{
                $optionRes['cate']['title'] = '全部';
                $optionRes['cate']['value'] = -1;
            }
            if(!empty($data['search']['cityItem']) || (isset($data['search']['cityPicker']) && $data['search']['cityPicker']['value'] != -1)){
                //国内
                if($data['search']['cityPicker']['value'] == 2){
                    $where[] = ['country', '=', '中国'];

                    if($data['search']['cityPicker']['value'] == 2){
                        $optionRes['city']['title'] = '中国';
                        $optionRes['city']['value'] = 2;
                    }
                    $province = array_column($data['search']['cityItem'], 'title');

                    if(!empty($data['search']['cityItem']) && !in_array('全部', $province)){
                        $where[] = ['province', 'in', $province];
                    }
                }
                if($data['search']['cityPicker']['value'] == 1){
                    $where[] = ['country', '=', '中国'];
                    $optionRes['city']['title'] = '热门';
                    $optionRes['city']['value'] = 1;
                    $province = array_column($data['search']['cityItem'], 'title');

                    if(!empty($data['search']['cityItem']) && !in_array('全部', $province)){
                        $where[] = ['province', 'in', $province];
                    }
                }
                //海外
                if($data['search']['cityPicker']['value'] == 3){
                    $where[] = ['country', '<>', '中国'];
                    $optionRes['city']['title'] = '海外';
                    $optionRes['city']['value'] = 3;
                    $country = array_column($data['search']['cityItem'], 'title');
                    if(!empty($data['search']['cityItem']) && !in_array('全部', $country) ){
                        $where[] = ['country', 'in', $country];

                    }

                }
            }
            if(!empty($data['search']['dateItem']) || (isset($data['search']['datepicker']['value']) && $data['search']['datepicker']['value'] != -1) ){
                //时间赛选
                $year = $data['search']['datepicker']['value'];
                $month = array_column($data['search']['dateItem'], 'value');
                if(!empty($data['search']['dateItem']) && !in_array('-1', $month)){
                    $min = date('Y-m-d', strtotime($year. '-'. min($month) . '-01'));
                    $minMonth = date('Y-m-d', strtotime($year. '-'. max($month)));
                    $max = date('Y-m-d', strtotime("$minMonth +1 month -1 day"));
                    $where[] = ['start_time', 'between', [$min, $max]];
                }else{
                    $min = $year. '-'. '01' . '-01';
                    $max = $year. '-'. '12' . '-31';
                    $where[] = ['start_time', 'between', [$min, $max]];
                }
                $optionRes['date']['title'] = $year;
                $optionRes['date']['value'] = $year;
            }
        }else{
            if(!empty($data['cityGroup']) && empty($data['search'])){
                if($data['cityGroup'] == 3){
                    $where[] = ['country', '<>', '中国'];
                    $optionRes['city']['title'] = '海外';
                    $optionRes['city']['value'] = 3;
                }else if($data['cityGroup'] == 2){
                    $where[] = ['country', '=', '中国'];
                    $optionRes['city']['title'] = '中国';
                    $optionRes['city']['value'] = 2;
                }else if($data['cityGroup'] == 1){
//                $where[] = ['country', '=', '中国'];
                    $optionRes['city']['title'] = '热门';
                    $optionRes['city']['value'] = 1;
                }else{
                    $optionRes['city']['title'] = '全部';
                    $optionRes['city']['value'] = -1;
                }
            }
            if(!empty($data['cateId'])){
                if($data['cateId'] != -1){
                    $cate = config('data.activity_type');
//            $where[] = ['type', 'in', $data['cateId']];
                    if($data['cateId'] == 'no_visa'){
                        $activityIds = db('lite_activity_cate')->where('cate_id', '<>', 8)->column('id, activity_id', 'id');
                        $where[] = ['id', 'in', array_unique($activityIds)];
                        $optionRes['cate']['title'] = '全部';
                        $optionRes['cate']['value'] = -1;
                    }else{
                        $activityIds = db('lite_activity_cate')->where('cate_id', '=', $data['cateId'])->column('id, activity_id', 'id');
                        $where[] = ['id', 'in', array_unique($activityIds)];
                        $optionRes['cate']['title'] = $cate[$data['cateId']]['name'];
                        $optionRes['cate']['value'] = $data['cateId'];
                    }

                }else{
                    $optionRes['cate']['title'] = '全部';
                    $optionRes['cate']['value'] = -1;
                }
            }
        }

        //搜索
        $whereOr = [];
        if(!empty($data['keyword'])){
            $where[] = ['name', 'like', '%'. $data['keyword']. '%'];
            $whereOr[] = ['country', 'like', '%'. $data['keyword']. '%'];
        }



        //总数量
        $totalSize = db($this->table)->where($where)->whereOr($whereOr)->count();
//        $sql = db::table($this->table)->where($where)->whereOr($whereOr)->getLastSql();
//        var_dump();exit;

        //当前页码
        $current_page = $this->request->param('pageNum', 1);
        //分页大小
        $size = $this->request->param('size', 3);

        $list = db($this->table)->where($where)->whereOr($whereOr)->limit(($current_page - 1) * $size, $size)->order('sort', 'desc')->order('id', 'desc')->select();
//        $activityIds = array_column($list, 'id');
        //获取最低价格
//        $groupMinPrice = db($this->groupTable)->where(['activity_id' => $activityIds])->group('activity_id')->column('activity_id,min(price)');
//        $packageMinPrice = db($this->packageTable)->where(['activity_id' => $activityIds])->group('activity_id')->column('activity_id,min(price)');

        foreach ($list as $key => $val){
            $applyEndTime = strtotime($list[$key]['apply_end_time']);
//           if($applyEndTime > time()){
//               $dateFormat = $this->getDateFormat($applyEndTime);
//               $list[$key]['day'] = $dateFormat['day'];
//               $list[$key]['hour'] = $dateFormat['hour'];
//               $list[$key]['minute'] = $dateFormat['minute'];
//           }else{
//               $this->setActivityStatus($val['id'], $applyEndTime);
//               unset($list[$key]);
//               continue;
//           }

//           $list[$key]['activityId'] = $val['id'];

            $dateFormat = $this->getDateFormat($applyEndTime);
            $list[$key]['day'] = $dateFormat['day'];
            $list[$key]['hour'] = $dateFormat['hour'];
            $list[$key]['minute'] = $dateFormat['minute'];

            $list[$key]['start_time'] = substr($list[$key]['start_time'], 0, 10);
//           $list[$key]['minPrice'] = min([isset($groupMinPrice[$val['id']]) ? $groupMinPrice[$val['id']]: 0, isset($packageMinPrice[$val['id']]) ? $packageMinPrice[$val['id']]: 0]);
//            if(isset($packageMinPrice[$val['id']]) && isset($groupMinPrice[$val['id']])){
//                $list[$key]['minPrice'] = min([$groupMinPrice[$val['id']], $packageMinPrice[$val['id']] ]);
//            }else{
//                $list[$key]['minPrice'] = isset($groupMinPrice[$val['id']]) ? $groupMinPrice[$val['id']]:0;
//            }
            $list[$key]['minPrice'] = $list[$key]['show_price'];
            $list[$key]['minPrice'] = round($list[$key]['minPrice'], 1);
            $list[$key]['pic'] = $this->getImageDir($list[$key]['pic']);
            //城市
            if($val['country'] == '中国'){
                $city = [$val['province'], $val['city']];
                $list[$key]['city'] = implode('-', array_filter($city));
            }else{
                $city = [$val['country'], $val['province'], $val['city']];
                $list[$key]['city'] = implode('-', array_filter($city));
            }
        }

        $res = [];

        $res['option'] = isset($optionRes) ? $optionRes:[];
        $res['list'] = $list;
        $res['current_page'] = $current_page;
        $res['totalSize'] = $totalSize;
        $res['pageSize'] = ceil($totalSize / $size);

        $this->success('', $res);
    }

    private function getRelationGoodsData($id, $getDetail = false)
    {
        $data = db($this->goodsTable)->where(['is_deleted' => 0, 'activity_id' => $id])->select();
        $productIds = array_column($data, 'product_id');
        $goodsInfo = db('store_goods')->where(['is_deleted' => 0, 'status' => 1])->where('id', 'in', $productIds)->column('id,title,lists,logo,specs','id');
        $goodsIds = array_column($goodsInfo, 'id');
        $listInfo = db('store_goods_list')->where(['status' => 1])->where('goods_id', 'in', $goodsIds)->column('id,goods_id, goods_spec,price_market,price_selling','id');
        foreach ($data as $key => $goods){
            if(!isset($goodsInfo[$goods['product_id']])){
                unset($data[$key]);
                continue;
            }
            $data[$key]['id'] = $goodsInfo[$goods['product_id']]['id'];
            $data[$key]['title'] = $goodsInfo[$goods['product_id']]['title'];
            $lists = json_decode($goodsInfo[$goods['product_id']]['lists'], true)[0][0];
            $data[$key]['price_market'] = $lists['market'];
            $data[$key]['price_selling'] = $lists['selling'];
            if($getDetail){
                $data[$key]['lists'] = json_decode($goodsInfo[$goods['product_id']]['lists'], true);
                $data[$key]['specs'] = json_decode($goodsInfo[$goods['product_id']]['specs'], true);
                $attr = [];
                foreach ($listInfo as $listKey => $list){
                    if($list['goods_id'] == $goodsInfo[$goods['product_id']]['id']){
                        $attr[$list['goods_spec']] = $list;
                    }
                }
                $data[$key]['list'] = $attr;
            }
            $data[$key]['logo'] = $goodsInfo[$goods['product_id']]['logo'];
        }

        return array_values($data);
    }

    //获取装备尺码
    public function getGoodsAttr()
    {
        $productId = $this->request->param('product_id');
        $goods = $this->getRelationGoodsData($productId, true);
        $res = [];
        foreach ($goods as $key => $value){
            $res[$key] = $value;
            $res[$key]['id'] = $value['id'];
            $res[$key]['name'] = $value['title'];
            $res[$key]['item_open'] = false;
            $item = [];
            foreach ($value['specs'] as $specKey => $spec){
                $item[$specKey]['item_name'] = $spec['name'];
                $item[$specKey]['item_value'] = array_column($spec['list'], 'name');
            }
            $res[$key]['item'] = $item;
            $res[$key]['list'] = $value['list'];
        }

        $this->success('', $res);
    }

}